<?php
class BaseController extends BaseModelObject {
    /**
     * object sigle-on-instance
     * @var object
     */
	protected static $_instance = NULL;
	/**
	 * controller's prefixed name
	 * @var string
	 */
	protected static $_state    = DEFAULT_STATE;
	/**
	 * controller's method
	 * @var string
	 */
	protected static $_action   = DEFAULT_ACTION;
	/**
	 * uri seperator, eg: get_user
	 * @var const
	 */
	const     URISEPERATOR = '_';
	
	public function __construct() {
		if( is_null(self::$_instance) ) {
			$args = func_get_args();
			$state = $args[0];
			$action = $args[1];
			$class = $this->toString();
			$methods = get_class_methods($class);
			
			if( isset($state) ) {
				self::$_state = $state;
			}
			if( isset($action) && !in_array($action, $methods) ) {//self protect
				self::$_action = $action;
			}
			self::$_instance = 1;
		}
	}
	/**
	 * get the controller prefix name by state
	 */
	public function getStateClass() {
	
		$state = explode(self::URISEPERATOR, self::$_state);
		for($i = 0, $len = count($state); $i < $len; $i++ ) {
			$state[$i] = ucfirst(strtolower($state[$i]));
		}
		return implode('', $state);
	}
    /**
     * get the method name by action
     */
	public function getActionMethod() {

		$action = explode(self::URISEPERATOR, self::$_action);
		$action[0] = strtolower($action[0]);
		for($i = 1, $len = count($action); $i < $len; $i++ ) {
			$action[$i] = ucfirst(strtolower($action[$i]));
		}
		return implode('', $action);
	}
	/**
	 * key method, every uri must do this
	 */
	public function runCommand() {
		$action = $this->getActionMethod();
		if( method_exists($this, $action) ) {
			call_user_func_array(array(&$this, $action),array());
		}
		else {
			$this->error('missingAction');
		}
	}
}